package main

import (
	"fmt"
	"io"
	"math"
	"net/http"
)

const (
	angle   = math.Pi / 6
	width   = 1000
	height  = 1000
	xyrange = 30.0 // x, y  变化范围，大约 2.4 个周期
	xscale  = width / 2 / xyrange
	yscale  = height / 2 / xyrange
	cells   = 100
)

var sin30, cos30 = math.Sin(angle), math.Cos(angle)

func draw(w io.Writer) {
	fmt.Fprintf(w, "<svg xmlns='http://www.w3.org/2000/svg' style='stroke: grey; fill:white; stroke-width: 0.7' width='1000' height='1000'>\n")
	for i := 0; i < cells; i++ {
		for j := 0; j < cells; j++ {
			xx1, yy1 := corner(i, j)
			xx2, yy2 := corner(i, j+1)
			xx3, yy3 := corner(i+1, j+1)
			xx4, yy4 := corner(i+1, j)
			fmt.Fprintf(w, "<polygon points='%g,%g %g,%g %g,%g %g,%g' fill='#CCFFFF'/>\n",
				xx1, yy1,
				xx2, yy2,
				xx3, yy3,
				xx4, yy4)
		}
	}
	fmt.Fprintf(w, "</svg>\n")
}

// 计算第 (i, j) 个小方块的角点坐标
func corner(i, j int) (float64, float64) {
	// 将 i, j 映射到 xyrange 这个范围，然后再计算坐标
	x := xyrange * (float64(i)/cells - 0.5)
	y := xyrange * (float64(j)/cells - 0.5)
	xx, yy := project(x, y, f(x, y))
	return width/2 + xx*xscale, height/2 + yy*yscale
}

func project(x, y, z float64) (float64, float64) {
	xx := x*cos30 - y*cos30
	yy := x*sin30 + y*sin30 - z
	return xx, yy
}

func f(x float64, y float64) float64 {
	r := math.Hypot(x, y)
	z := math.Sin(r) / r
	return 10 * z
}

func handle(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "image/svg+xml")
	draw(w)
}

func main() {
	http.HandleFunc("/", handle)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Printf("%v", err)
	}
}
